package com.mall.cart.service.impl;

import com.google.common.collect.Lists;
import com.mall.cart.mapper.CartMapper;
import com.mall.cart.model.Cart;
import com.mall.cart.service.ICartService;
import com.mall.goods.feign.SkuFeign;
import com.mall.goods.model.Sku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Darren
 * @date 2022-08-29 10:00
 * Description：购物车id是id+username
 */
@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addCart(String id, String userName, Integer num) {
        // 先删除，后增加
        cartMapper.deleteById(id + userName);
        if (num > 0) {
            Sku sku = skuFeign.getById(id).getData();
            if (sku != null) {
                Cart cart = new Cart();
                cart.set_id(id + userName);
                cart.setUserName(userName);
                cart.setName(sku.getName());
                cart.setPrice(sku.getPrice());
                cart.setImage(sku.getImage());
                cart.setSkuId(sku.getId());
                cart.setNum(num);
                cartMapper.save(cart);
            }
        }
    }

    @Override
    public List<Cart> list(String userName) {
        Cart cart = new Cart();
        cart.setUserName(userName);
        return cartMapper.findAll(Example.of(cart), Sort.by("_id"));
    }

    @Override
    public List<Cart> list(List<String> ids) {
        return Lists.newArrayList(cartMapper.findAllById(ids));
    }

    @Override
    public void deleteCart(List<String> ids) {
        mongoTemplate.remove(Query.query(Criteria.where("_id").in(ids)), Cart.class);
    }

}
